# -*- coding: utf-8 -*-
# ㊎ Author : XMZ
# ㊍ Time : 2021/5/3 16:25
# ㊌ File : RabbitMQ -> consumer_a.py
# ㊋ IDE :  PyCharm
# ㊏ 
import os
import sys
import time

import pika

self_path = os.path.dirname(os.path.abspath(__file__))
father_path = os.path.dirname(self_path)
parent_path = os.path.dirname(father_path)
sys.path.append(self_path)
sys.path.append(father_path)
sys.path.append(parent_path)


class MQ(object):
    def __init__(self):
        hosts = "10.0.2.22"
        name = "admin"
        pwd = "123456"
        credential = pika.PlainCredentials(username=name, password=pwd)
        try:
            self.connection = pika.BlockingConnection(
                pika.ConnectionParameters(
                    host=hosts,
                    credentials=credential,
                    heartbeat=0,
                ))

            self.channel = self.connection.channel()
            self.queue_name = "TEST_QUEUE"
            self.channel.queue_declare(queue=self.queue_name)
        except Exception as e:
            return e

    @staticmethod
    def rollback(ch, method, properties, body):
        print(f"从队列提取数据：{body.decode()},    休息时间：{len(body)}")
        time.sleep(0.15)
        ch.basic_ack(delivery_tag=method.delivery_tag)

    def __handle_data(self):
        # 设置公平调度
        self.channel.basic_qos(prefetch_count=1)
        # 设置监听队列，队列消息处理函数，确认机制，是否排他
        self.channel.basic_consume(
            queue=self.queue_name,
            on_message_callback=self.rollback,
            auto_ack=False,
            exclusive=False,
        )

    def start(self, retry=2):
        try:
            self.__handle_data()
            # 启动并开始处理消息
            self.channel.start_consuming()
        except Exception as e:
            print(f"正在重试；{retry}, ERROR: {e}")
            time.sleep(10)
            e = self.__init__()
            print(f"第{retry}次重试失败;   __init__:{e}")
            return "重试失败了-可能是断网了哦 ！！！ " if retry == 0 else self.start(retry - 1)

    def end(self):
        self.connection.close()


if __name__ == '__main__':
    m = MQ()
    print(m.start())
    m.end()
